package com.atstudent.gmall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atstudent.gmall.common.constant.GmallConstant;
import com.atstudent.gmall.common.execption.GmallException;
import com.atstudent.gmall.common.result.ResultCodeEnum;
import com.atstudent.gmall.user.dto.UserLoginDto;
import com.atstudent.gmall.user.vo.UserLoginSuccessVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atstudent.gmall.user.entity.UserInfo;
import com.atstudent.gmall.user.service.UserInfoService;
import com.atstudent.gmall.user.mapper.UserInfoMapper;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import springfox.documentation.spring.web.json.Json;

import java.util.Random;
import java.util.UUID;

/**
* @author 薛有朋
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2025-03-25 22:40:32
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService{

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    RedisTemplate<String , String> redisTemplate = new RedisTemplate<>();

    @Override
    public UserLoginSuccessVo login(UserLoginDto userLoginDto) {

        //根据用户名查询数据库
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getLoginName , userLoginDto.getLoginName());
        UserInfo userInfo = userInfoMapper.selectOne(lambdaQueryWrapper);

        //判断是否存在这个用户
        if (userInfo == null){
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR);
        }

        //判断密码是否正确
        String passwd = userLoginDto.getPasswd();
        //把密码转成字节数组  通过md5加密
        String md5Passwd = DigestUtils.md5DigestAsHex(passwd.getBytes());
        if (!md5Passwd.equals(userInfo.getPasswd())){
            throw new GmallException(ResultCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //密码正确 生成token令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        //把token存入到Redis中
        redisTemplate.opsForValue().set(GmallConstant.REDIS_USER_LOGIN_PRE + token , JSON.toJSONString(userInfo));

        //构建vo实体类 进行返回
        UserLoginSuccessVo userLoginSuccessVo = new UserLoginSuccessVo();
        userLoginSuccessVo.setToken(token);
        userLoginSuccessVo.setNickName(userInfo.getNickName());

        return userLoginSuccessVo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(GmallConstant.REDIS_USER_LOGIN_PRE + token);
    }
}




